<template>
    <form >
      <div class="form-item">
        <label for="username">用户名</label>
        <input 
          type="text" 
          id="username" 
          v-model="form.username" 
          required 
          placeholder="请输入用户名"
        />
        <span class="error" v-if="errors.username">{{ errors.username }}</span>
      </div>
  
      <div class="form-item">
        <label for="password">密码</label>
        <input 
          type="password" 
          id="password" 
          v-model="form.password" 
          required 
          placeholder="请输入密码"
        />
        <span class="error" v-if="errors.password">{{ errors.password }}</span>
      </div>
  
      <button type="submit" @click="handleSubmit" :disabled="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </form>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import axios from 'axios';
  import {useRouter} from 'vue-router';
  import { useUserStore } from '@/store/userstore'
  const userStore = useUserStore()
  const router =useRouter();
  const form = ref({
    username: '',
    password: ''
  })
  
  const errors = ref({})
  const loading = ref(false)
  

  const validate = () => {
    errors.value = {}
    
    if (!form.value.username) {
      errors.value.username = '用户名不能为空'
    }
    
    if (!form.value.password) {
      errors.value.password = '密码不能为空'
    } else if (form.value.password.length < 6) {
      errors.value.password = '密码长度不能少于6位'
    }
    
    return Object.keys(errors.value).length === 0
  }
  
  const handleSubmit = async () => {
    if (!validate()) return
    
    loading.value = true

      const response = await axios.post(`http://localhost:8080/user/login?userName=${form.value.username}&password=${form.value.password}`);
      if (response.data.code==200) {
        userStore.setUsername(response.data.data.username),
        userStore.setId(response.data.data.id)
        router.push('/option'); // 登录成功后跳转到首页
        }else{
            console.log(response.data);

        }
}
  

  </script>
  
  <style scoped>
  .form-item {
    margin-bottom: 20px;
  }
  
  label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    color: #333;
  }
  
  input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 16px;
  }
  
  input:focus {
    outline: none;
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
  
  .error {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 5px;
    display: block;
  }
  
  button {
    width: 100%;
    padding: 12px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  
  button:hover {
    background-color: #66b1ff;
  }
  
  button:disabled {
    background-color: #a0cfff;
    cursor: not-allowed;
  }
  </style>